package com.jili.helloword.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author: Jili
 * @date: Created on 2022/4/20 16:59
 */
@ChannelHandler.Sharable
public class HandlerServerHello extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //处理收到消息数据，并反馈给客户端
        ByteBuf in = (ByteBuf)msg;
        System.out.println("收到客户端发来的消息："+in.toString(CharsetUtil.UTF_8));

        //写入并发消息给客户端
        ctx.writeAndFlush(Unpooled.copiedBuffer("我是服务端，收到消息！",CharsetUtil.UTF_8));



    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //出现异常的时候执行（打印并关闭通道）
        cause.printStackTrace();
        ctx.close();
    }
}
